package org.kabeja.parser;

import org.kabeja.parser.objects.DXFObjectHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shutao
 * @since 2022/4/25 14:24
 */
public class DXFObjectsSectionHandler extends AbstractSectionHandler implements HandlerManager {
    private static String SECTION_KEY = "OBJECTS";
    public static final int OBJECT_START = 0;
    private Map<String, Object> handlers = new HashMap<>();
    private DXFObjectHandler handler;
    private boolean parseObject = false;

    public DXFObjectsSectionHandler() {
    }

    @Override
    public void endSection() {
        this.endObject();
    }

    @Override
    public String getSectionKey() {
        return SECTION_KEY;
    }

    @Override
    public void parseGroup(int var1, DXFValue var2) {
        if (var1 == OBJECT_START) {
            this.endObject();
            if (this.handlers.containsKey(var2.getValue())) {
                this.parseObject = true;
                this.handler = (DXFObjectHandler)this.handlers.get(var2.getValue());
                this.handler.setDXFDocument(this.doc);
                this.handler.startObject();
            } else {
                this.parseObject = false;
            }
        } else if (this.parseObject) {
            this.handler.parseGroup(var1, var2);
        }

    }

    @Override
    public void startSection() {
        this.parseObject = false;
    }

    @Override
    public void releaseDXFDocument() {
        this.doc = null;
    }

    @Override
    public void addHandler(Handler var1) {
        DXFObjectHandler var2 = (DXFObjectHandler)var1;
        var2.setDXFDocument(this.doc);
        this.handlers.put(var2.getObjectType(), var2);
    }

    protected void endObject() {
        if (this.parseObject) {
            this.handler.endObject();
            this.doc.addDXFObject(this.handler.getDXFObject());
        }

    }
}
